package com.sinosoft.perfect.system._.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

public class FileUtil {
	
	/**
	 * 文件转化为字节数组
	 */
	public static byte[] getBytesFromFile(File f) {
		byte[] bytes = null;
		try {
			InputStream is = new FileInputStream(f);
			long length = f.length();
			if (length > Integer.MAX_VALUE) {
				throw new IOException("file is too large ");
			}
			bytes = new byte[(int) length];
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}
			if (offset < bytes.length) {
				throw new IOException("Could not completely read file " + f.getName());
			}
			is.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bytes;
	}
	
	public static void createFile(byte[] b, String outputFilePath, String outputFilename) throws IOException {
		String outputFile = (outputFilePath + File.separator + outputFilename);
		File newFile = getFileFromBytes(b, outputFile);
		newFile.createNewFile();
	}
	
	/**
	 * 把字节数组保存为一个文件
	 */
	public static File getFileFromBytes(byte[] b, String outputFile) {
		File file = new File(outputFile);
		try {
			OutputStream out = new FileOutputStream(file);
			out.write(b);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return file;
	}
	
	/**
	 * 从字节数组获取对象
	 */
	public static Object getObjectFromBytes(byte[] objBytes) throws Exception {
		if (objBytes == null || objBytes.length == 0) {
			return null;
		}
		ByteArrayInputStream bi = new ByteArrayInputStream(objBytes);
		ObjectInputStream oi = new ObjectInputStream(bi);
		return oi.readObject();
	}
	
	/**
	 * 从对象获取一个字节数组
	 */
	public static byte[] getBytesFromObject(Serializable obj) throws Exception {
		if (obj == null) {
			return null;
		}
		ByteArrayOutputStream bo = new ByteArrayOutputStream();
		ObjectOutputStream oo = new ObjectOutputStream(bo);
		oo.writeObject(obj);
		return bo.toByteArray();
	}
}
